const {getAccountList, login, updateAccountPassword, deleteAccount, getAccountDetail} = require('../controller/user')
const {delStudentByUsername} = require("../controller/student");
const {delCoachByUsername} = require("../controller/coach");
const Response = require('../common/Response')
const router = require('koa-router')()

router.prefix('/api/user')

// 登录的验证
router.post('/validate', async (context, next) => {
  let path = context.request.body.path.split('/')
  if (context.session.username) {
    if (path[1] !== context.session.rolename) {
      context.body = Response.failure('请求页面与角色不符，请先登录...')
    } else {
      context.body = Response.success()
    }
  } else {
    context.body = Response.failure('请先登录...')
  }
})
// 账户登录
router.post('/login', async (context, next) => {
  const row = await login(context.request.body)
  if (row.username) {
    // 登录成功设置session，自动同步到redis
    context.session.username = row.username
    context.session.rolename = row.rolename
    context.body = Response.success('登录成功')
  } else {
    context.body = Response.success('用户名或密码错误')
  }
});
// 获取所有账户信息
router.get('/list', async (context, next) => {
  const rows = await getAccountList()
  context.body = Response.success(rows)
});
// 修改账户密码
router.post('/update', async (context, next) => {
  const val = await updateAccountPassword(context.request.body)
  if (val) {
    context.body = Response.success('修改账户密码成功')
  } else {
    context.body = Response.success('修改账户密码失败')
  }
});
// 删除账户信息，删除对应学员或教练信息
router.post('/del/:id', async (context, next) => {
  const val = await deleteAccount(context.params.id)
  if (val) {
    if (context.request.body.rolename === 'student') {
      const StudentValue = await delStudentByUsername(context.request.body.identify)
      if (StudentValue) {
        context.body = Response.success('删除账户成功')
      }
    } else {
      const CoachValue = await delCoachByUsername(context.request.body.identify)
      if (CoachValue) {
        context.body = Response.success('删除账户成功')
      }
    }
  } else {
    context.body = Response.failure('删除账户失败')
  }
});
// 获取账户详细信息
router.get('/detail', async (context, next) => {
  const row = await getAccountDetail(context.session.username)
  if (row.username) {
    context.body = Response.success(row)
  } else {
    context.body = Response.failure('获取账户详细信息失败')
  }
})

module.exports = router;
